
from datetime import datetime, timedelta
from typing import Any, Union, Dict
from jose import jwt
from starlette.responses import JSONResponse
from initialization import ACCESS_TOKEN_EXPIRE_MINUTES, SECRET_KEY, ALGORITHM

# 生成token
async def create_access_token(subject: Union[str, Any], expires_delta: timedelta = None) -> Dict[str, Any]:
    """
    # 生成token
    :param subject: 保存到token的值
    :param expires_delta: 过期时间
    :return:
    """
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + datetime.timedelta(
            minutes=ACCESS_TOKEN_EXPIRE_MINUTES
        )
    to_encode = {"exp": expire, "sub": str(subject)}
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return {"token":encoded_jwt, "expires_delta":expires_delta}

# 解析token
async def analysis_token(token):
    try:
        payload = jwt.decode(
            token,
            SECRET_KEY, algorithms=ALGORITHM
        )
        return payload
    except (jwt.JWTError, jwt.ExpiredSignatureError, AttributeError):
        # 抛出自定义异常， 然后捕获统一响应
        return False

async def verify_token_format(tokenStr):
    if tokenStr is None or tokenStr == "":
        return JSONResponse(content={"code": 604, "data": None, "message": "token不能为空"})

    tokenList = tokenStr.split(" ", 2)
    if len(tokenList) != 2:
        return JSONResponse(content={"code": 604, "data": None, "message": "token格式错误"})

    if tokenList[0] != "Bearer":
        return JSONResponse(content={"code": 604, "data": None, "message": "token头错误"})

    return tokenList



